from flask import Flask, request, render_template
import os
from ip_querier import get_ip_info, batch_process_ip, format_ip_info

app = Flask(__name__)

# 为不同的IP信息键创建对应的Font Awesome图标映射
KEY_ICONS = {
    "国家/地区": "fa-globe-asia",
    "省/州": "fa-map-marked-alt",
    "城市": "fa-city",
    "区域": "fa-map-marker-alt",
    "邮政编码": "fa-mail-bulk",
    "经纬度": "fa-map-pin",
    "ISP提供商": "fa-network-wired",
    "组织": "fa-building",
    "AS编号": "fa-server",
    "移动网络": "fa-mobile-alt",
    "代理": "fa-shield-alt",
    "托管服务": "fa-database"
}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/query', methods=['POST'])
def query_ip():
    ip_address = request.form.get('ip_address')
    if ip_address:
        ip_info = get_ip_info(ip_address)
        # 解析IP信息为结构化数据
        formatted_info = parse_ip_info(ip_info, ip_address)
        return render_template('result.html', 
                              ip_address=ip_address, 
                              info_items=formatted_info,
                              key_icons=KEY_ICONS)
    return "没有提供 IP 地址。"

@app.route('/batch', methods=['POST'])
def batch_query():
    file = request.files['ip_file']
    if file:
        # 创建 uploads 目录（如果不存在）
        os.makedirs('uploads', exist_ok=True)
        
        file_path = os.path.join('uploads', file.filename)
        file.save(file_path)
        raw_results = batch_process_ip(file_path)
        
        # 处理结果，为每个 IP 添加结构化数据
        results = []
        for result in raw_results:
            ip = result["ip"]
            ip_info = result["info"]
            parsed_info = parse_ip_info(ip_info, ip)
            results.append({
                "ip": ip,
                "parsed_info": parsed_info
            })
            
        return render_template('batch_result.html', 
                              results=results,
                              key_icons=KEY_ICONS)
    return "没有上传文件。"

def parse_ip_info(ip_info, ip_address):
    """将原始IP信息解析为键值对列表，用于模板渲染"""
    if "error" in ip_info:
        return [("错误", ip_info['error'])]
    
    parsed_info = []
    
    # 添加基本信息
    parsed_info.append(("国家/地区", ip_info.get('country', '未知')))
    parsed_info.append(("省/州", ip_info.get('regionName', '未知')))
    parsed_info.append(("城市", ip_info.get('city', '未知')))
    
    # 添加详细本地信息
    if ip_info.get('district'):
        parsed_info.append(("区域", ip_info['district']))
    
    if ip_info.get('zip'):
        parsed_info.append(("邮政编码", ip_info['zip']))
    
    # 添加坐标信息
    if ip_info.get('lat') and ip_info.get('lon'):
        parsed_info.append(("经纬度", f"{ip_info['lat']}, {ip_info['lon']}"))
    
    # 添加ISP信息
    if ip_info.get('isp'):
        parsed_info.append(("ISP提供商", ip_info['isp']))
    
    if ip_info.get('org'):
        parsed_info.append(("组织", ip_info['org']))
    
    if ip_info.get('as'):
        parsed_info.append(("AS编号", ip_info['as']))
    
    # 添加其他信息
    if ip_info.get('mobile') == True:
        parsed_info.append(("移动网络", "是"))
    
    if ip_info.get('proxy') == True:
        parsed_info.append(("代理", "是"))
    
    if ip_info.get('hosting') == True:
        parsed_info.append(("托管服务", "是"))
    
    return parsed_info

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
